<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>编辑用户</title>
    <link href="/layui/css/layui.css" rel="stylesheet">
</head>
<body>
<div class="layui-margin-3 layui-anim layui-anim-upbit" style="margin-top: 15px;">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <form class="layui-form layui-form-pane">
                <div class="layui-form-item layui-col-space20">

                    <!--左侧上传头像-->
                    <div class="layui-col-md4">
                        <div class="layui-col-md12">
                            <div class="layui-panel" style="aspect-ratio: 1/1;">
                                <img id="ID-upload-demo-img" th:src="${user.base64}" style="width: 100%; height: 100%;">
                                <input type="text" name="base64" id="base64" value="0" hidden="hidden">
                            </div>
                        </div>
                        <div class="layui-col-md12" style="margin-top: 10px;" th:if="${openType==1}">
                            <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo">
                                <div class="layui-progress-bar" lay-percent=""></div>
                            </div>
                        </div>
                        <div class="layui-col-md12" style="margin-top: 10px;" th:if="${openType==1}">
                            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-btn-fluid" id="ID-upload-demo-btn">
                                <i class="layui-icon layui-icon-upload"></i> 上传用户照片
                            </button>
                        </div>
                        <div id="ID-upload-demo-text" class="layui-col-md12" style="margin-top: 10px;" th:if="${openType==1}"></div>
                    </div>

                    <!--右侧基本信息-->
                    <div class="layui-col-md4">
                        <label class="layui-form-label">用户姓名：</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" th:value="${user.name}" autocomplete="off" class="layui-input" lay-verify="required" th:disabled="${openType==2}">
                        </div>
                    </div>

                    <div class="layui-col-md4">
                        <label class="layui-form-label">电子邮箱：</label>
                        <div class="layui-input-block">
                            <input type="email" name="email" th:value="${user.email}" autocomplete="off" class="layui-input" lay-verify="required|email" th:disabled="${openType==2}">
                        </div>
                    </div>

                    <div class="layui-col-md4">
                        <label class="layui-form-label">身份证号：</label>
                        <div class="layui-input-block">
                            <input type="text" name="card" th:value="${user.card}" id="card" autocomplete="off" class="layui-input" lay-verify="required|identity" th:disabled="${openType==2}">
                        </div>
                    </div>

                    <div class="layui-col-md4">
                        <label class="layui-form-label">账号密码：</label>
                        <div class="layui-input-block">
                            <input type="password" name="password" th:value="${user.password}" id="password" class="layui-input" th:disabled="${openType==2}">
                        </div>
                    </div>

                    <div class="layui-col-md4">
                        <label class="layui-form-label">用户身份：</label>
                        <div class="layui-input-block">
                            <select name="type" lay-verify="required" th:disabled="${openType==2}">
                                <option th:each="i : ${identityList}" th:value="${i.id}" th:text="${i.name}" th:selected="${i.id == user.type}"></option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-col-md4">
                        <label class="layui-form-label">账号状态：</label>
                        <div class="layui-input-block">
                            <select name="status" th:disabled="${openType==2}">
                                <option value="1" th:selected="${user.status == 1}">可用</option>
                                <option value="2" th:selected="${user.status == 2}">停用</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-col-md8 layui-form-text">
                        <label class="layui-form-label">其他信息：</label>
                        <div class="layui-input-block">
                            <textarea name="other" th:text="${user.other}" class="layui-textarea" lay-verify="required" maxlength="500" rows="10" th:disabled="${openType==2}"></textarea>
                        </div>
                    </div>
                </div>

                <hr th:if="${openType==2}"/>

                <!--用户编号-->
                <input type="text" name="id" th:value="${user.id}" hidden="hidden">

                <div class="layui-form-item layui-col-space20" th:if="${openType==1}">
                    <div class="layui-col-md12" style="text-align: center;">
                        <button class="layui-btn layui-btn-danger" lay-submit lay-filter="toSet">更新用户信息</button>
                        <button type="reset" class="layui-btn layui-btn-warm">恢复原始信息</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="/layui/layui.js"></script>
<script>
    layui.use(['form', 'layer', 'jquery', 'upload', 'element'], function () {
        let form = layui.form;
        let layer = layui.layer;
        let $ = layui.jquery;
        let upload = layui.upload;
        let element = layui.element;

        let imageIsOk = true;

        // 单图片上传
        let uploadInst = upload.render({
            elem: '#ID-upload-demo-btn',
            url: '/uploadImage',
            size: 512, // 限制文件大小，单位KB
            before: function (obj) {
                // 预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#ID-upload-demo-img').attr('src', result); // 图片链接（base64）
                });
                element.progress('filter-demo', '0%'); // 进度条复位
            },
            done: function (res) {
                if (res === 0) {
                    imageIsOk = false;
                    return layer.msg('上传失败！');
                }
                layer.msg('上传成功！')
                $('#ID-upload-demo-text').html('上传成功😀');
                $('#base64').val('1');    // 表示用户头像重新上传了
            },
            error: function () {
                // 演示失败状态，并实现重传
                let demoText = $('#ID-upload-demo-text');
                demoText.html('<span style="color: #FF5722;">上传失败😥</span>&ensp;<a class="layui-btn layui-bg-purple layui-btn-xs demo-reload">点我重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            },
            // 进度条
            progress: function (n, elem, e) {
                element.progress('filter-demo', n + '%'); // 可配合 layui 进度条元素使用
            }
        });

        // 截取身份证号后6位作为密码
        $('#card').on('input', function () {
            $('#password').val($(this).val().slice(-6));
        });

        // 监听一级选择事件
        form.on('select(quiz1)', function (data) {
            let quiz1 = data.value;
            if (quiz1) {
                // 清空市和县/区的选择框
                $('#quiz2').html('<option value="">请选择市</option>');
                $('#quiz3').html('<option value="">请选择县/区</option>');
                form.render('select');

                // 请求二级列表
                $.get('/getArea/2/' + quiz1, function (data) {
                    $.each(data, function (index, info) {
                        $('#quiz2').append('<option value="' + info.code + '">' + info.name + '</option>');
                    });
                    form.render('select');
                }).fail(function () {
                    layer.msg('请求二级列表失败！', {icon: 2});
                });
            }
        });

        // 监听二级选择事件
        form.on('select(quiz2)', function (data) {
            let quiz2 = data.value;
            if (quiz2) {
                // 清空县区选择框
                $('#quiz3').html('<option value="">请选择县/区</option>');
                form.render('select');

                // 请求县区列表
                $.get('/getArea/3/' + quiz2, function (data) {
                    $.each(data, function (index, info) {
                        $('#quiz3').append('<option value="' + info.code + '">' + info.name + '</option>');
                    });
                    form.render('select');
                }).fail(function () {
                    layer.msg('请求三级列表失败！', {icon: 2});
                });
            }
        });

        // 拼接详细地址
        function splicingAddress() {
            let code = $('#quiz1').val() + '/' + $('#quiz2').val() + '/' + $('#quiz3').val();
            let address = $('#quiz1 option:selected').text() + $('#quiz2 option:selected').text() + $('#quiz3 option:selected').text() + '-' + $('#quiz4').val();
            $('#address').val(code + '/' + address);
        }

        // 监听三级选择事件
        form.on('select(quiz3)', function () {
            splicingAddress();
        });

        // 监听详细地址的输入事件
        $('#quiz4').on('input', function () {
            splicingAddress();
        });

        // 最终表单提交事件
        form.on('submit(toSet)', function (data) {

            if (!imageIsOk) {
                layer.msg('请上传用户头像！', {icon: 0});
                return false; // 阻止默认 form 跳转
            }

            let field = data.field; // 获取表单字段值

            $.ajax({
                url: '/doUserSet',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(field),
                success: function (res) {
                    if (res.code === 1) {
                        layer.msg('更新成功！', {icon: 1});

                        $.each(res.info, function (key, value) {
                            // 判断值是否为空（null、undefined、空字符串、空数组、空对象）
                            if (value === null || value === undefined || value === '' ||
                                (Array.isArray(value) && value.length === 0) ||
                                (typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0)) {
                                delete res.info[key]; // 删除空值属性
                            }
                        });

                        // 通过window.parent访问父页面的全局变量并修改
                        window.parent.parentData = res.info;

                        setTimeout(function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));    // 关闭弹出层
                        }, 2000);
                    } else {
                        layer.msg('更新失败！', {icon: 2});
                        imageIsOk = false;
                    }
                },
                error: function () {
                    layer.msg('Ajax请求异常！', {icon: 0});
                }
            });
            return false; // 阻止默认 form 跳转
        });
    });
</script>
</body>
</html>